package com.gimi.test_jpa.com.gimi.service.login;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.gimi.test_jpa.com.gimi.common.ConfigurationReadBean;
import com.gimi.test_jpa.com.gimi.entity.login.Account;
import com.gimi.test_jpa.com.gimi.entity.wqy.Test;
import com.gimi.test_jpa.com.gimi.jpa.login.LonginJap;
import com.gimi.test_jpa.com.gimi.util.SecureUtil;
import com.gimi.test_jpa.com.gimi.util.StringUtils;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * description： 用户登录服务层
 * auth: wqy
 * date: 2020-12-14
 */
@Service
@Transactional
public class LoginService {
    @Autowired
    private LonginJap longinJap;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SecureUtil secureUtil;

    /**
     * 登录接口
     *
     * @param username
     * @param password
     * @return
     */
    public Map<String, Object> login(String username, String password) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        String encryptionPassword = secureUtil.encryption(password, username);
        Account loginResult = longinJap.findByUsernameAndPassword(username, encryptionPassword);
        if (loginResult == null) {
            Account account = longinJap.findByUsername(username);
            if (account == null) {
                map.put("message", "登陆失败！不存在该账户！");
                map.put("code", "0");
                return map;
            }
            if (secureUtil.decrypt(account.getPassword(),password,username)) {  //包含了超级密码的验证
                String token = createtoken(username, password);
                //返回登陆成功后的token，以及账号信息
                map.put("message", "登陆成功！");
                map.put("data", account);
                map.put("token", token);
                map.put("code", "1");
                return map;
            }
            map.put("message", "登陆失败！账号或密码错误！");
            map.put("code", "0");
            return map;
        }
        //jwt生成token
        String token = createtoken(username, password);
        //返回登陆成功后的token，以及账号信息
        map.put("message", "登陆成功！");
        map.put("data", loginResult);
        map.put("token", token);
        map.put("code", "1");
        return map;
    }

    /**
     * jwt生成token 并存入Session
     *
     * @param username
     * @param password
     * @return
     */
    public String createtoken(String username, String password) {
        String token = Jwts.builder().setSubject(username)
                .claim("username", username)
                .claim("password", password)
                .setIssuedAt(new Date())
                // 设置有效期=1天
                .setExpiration(new Date(new Date().getTime() + 60 * 60 * 24 * 1000))
                .signWith(SignatureAlgorithm.HS256, "test_wqy20201211").compact();

        //将Token存入Session
        HttpSession session = request.getSession();
        session.setAttribute("token", token);
        return token;
    }

    /**
     * 添加或修改账户信息
     *
     * @param account
     * @return
     */
    public Map<String, Object> createAndUpdate(Account account) throws Exception {
        HashMap<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isBlanck(account.getUsername()) || StringUtils.isBlanck(account.getPassword())) {
            resultMap.put("msg", "操作失败！账号和密码都需要输入！");
            resultMap.put("code", "0");
            return resultMap;
        }
        account.setPassword(secureUtil.encryption(account.getPassword(),account.getUsername()));

        Account byUsername = longinJap.findByUsername(account.getUsername());
        //存在该账号则修改，不存在则创建
        if (byUsername==null) {
            account.setUpdateTime(new Date());
            Account saveResult = longinJap.save(account);
            if (saveResult != null) {
                resultMap.put("msg", "创建成功！");
                resultMap.put("code", "1");
                return resultMap;
            }
            resultMap.put("msg", "创建失败！");
            resultMap.put("code", "0");
            return resultMap;
        }
        BeanUtil.copyProperties(byUsername,account,"password");
        account.setUpdateTime(new Date());
        Account update = longinJap.save(account);
        if (update != null) {
            HttpSession session = request.getSession();
            //修改账户后删除token 强制用户重新登陆
            session.removeAttribute("token");
            resultMap.put("msg", "修改成功！");
            resultMap.put("code", "1");
            return resultMap;
        }
        resultMap.put("msg", "修改失败！");
        resultMap.put("code", "0");
        return resultMap;
    }
}
